package com.zs.leymovie;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Process;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnRadioGroupCheckedChange;
import com.zs.leymovie.fragment.ActivityFragment;
import com.zs.leymovie.fragment.LocationFragment;
import com.zs.leymovie.fragment.MeFragment;
import com.zs.leymovie.fragment.MovieFragment;
import com.zs.leymovie.fragment.TheatreFragment;
import com.zs.leymovie.service.ExampleUtil;
import com.zs.leymovie.utils.EventBusHelp;

import de.greenrobot.event.EventBus;


/**
 * * 作者：舒纲聿、张小冬
 * 时间：2015年8月17日20:53:28
 * 功能：系统数据展示界面
 */
@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    public static boolean isForeground = false;

    @ViewInject(R.id.main_rg_footer)
    private RadioGroup group;
    private Fragment[] fgs;
    private FragmentManager manager;
    private long currentTime = 0l;
    //用于fragment之间传值
    private String city_id;
    private String lngCityName;
    private String movie_id;
    private String movie_name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        registerMessageReceiver();  // 用于接收消息


        //注册EventBus，主要是用于接收消息，实现从影片界面跳转到影院界面
        EventBus.getDefault().register(this);

        Intent intent = getIntent();
        city_id = (intent.getStringExtra("cityid"));
        lngCityName = (intent.getStringExtra("lngCityName"));
        initFragment();
        manager = getSupportFragmentManager();
        manager.beginTransaction().add(R.id.main_container, fgs[0]).commit();
    }

    private void initFragment() {
        if (fgs == null) {
            fgs = new Fragment[5];
        }
        fgs[0] = new MovieFragment();
        fgs[1] = new TheatreFragment();
        fgs[2] = new LocationFragment();
        fgs[3] = new ActivityFragment();
        fgs[4] = new MeFragment();
    }


    @OnRadioGroupCheckedChange(R.id.main_rg_footer)
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        for (int i = 0; i < group.getChildCount(); i++) {    //遍历所有的单选按扭，一个按扭对应一个fragment
            Fragment fragment = fgs[i];            //拿到当前的Fragment对象
            if (group.getChildAt(i).getId() == checkedId) {
                if (!fragment.isAdded()) {                 //检查是否之前已经加载过，没有则加载
                    manager.beginTransaction().add(R.id.main_container, fragment).commit();  //加入到fragment管理器中
                }
                manager.beginTransaction().show(fragment).commit();    //显示Fragment
            } else {
                manager.beginTransaction().hide(fragment).commit();    //隐藏Fragment
            }
        }
    }

    /**
     * 退出时调用
     */
    @Override
    public void onBackPressed() {
        /*if (System.currentTimeMillis() - currentTime <= 2500) {
            this.finish();
        } else {
            currentTime = System.currentTimeMillis();
            // Toast.makeText(this, "你确定要退出吗", Toast.LENGTH_SHORT).show();
        }*/
        showTips();
    }

    //退出当前应用程序
    private void showTips() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提醒");
        builder.setMessage("是否退出程序");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                Process.killProcess(Process.myPid());
            }

        });
        builder.setNegativeButton("取消",

                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show(); // 显示对话框
    }

    //EventBus 接收事件
    public void onEventMainThread(EventBusHelp event) {
        movie_id = event.getMovie_id();
        movie_name = event.getMovie_name();
    }

    public String getCity_id() {
        return city_id;
    }

    public void setCity_id(String city_id) {
        this.city_id = city_id;
    }

    public String getLngCityName() {
        return lngCityName;
    }

    public void setLngCityName(String lngCityName) {
        this.lngCityName = lngCityName;
    }

    public String getMovie_id() {
        return movie_id;
    }

    public void setMovie_id(String movie_id) {
        this.movie_id = movie_id;
    }

    public String getMovie_name() {
        return movie_name;
    }

    public void setMovie_name(String movie_name) {
        this.movie_name = movie_name;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mMessageReceiver);
        EventBus.getDefault().unregister(this);//反注册EventBus
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    //极光推送Receiver
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!ExampleUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
            }
        }
    }
}
